<template>
    <div >
      <a-drawer
      width="1100"
      :maskClosable="false"
      :visible="dialogData.show"
      direction="rtl"
      @close="handleClose">
        <div slot="title">
          <span>新建支出</span>
        </div>
        <el-row style="width:920px;padding-bottom:150px;height:100%;overflow-y:auto">
          <el-col :span="19">
             <el-form :model="parames" size="small" :rules="rules" label-position="left" ref="parames" label-width="84px" class="addForm">
                <el-row style="padding: 0 40px" :gutter="20">
                  <a-collapse :defaultActiveKey="activeNames" :bordered="false">
                    <a-collapse-panel class="marginB10" header="基本信息" key="1">
                      <el-col :span="12" style="margin-top:15px">
                        <el-form-item label="支出科目:" prop="causeSubjectIds">
                          <el-cascader
                            style="width:230px"
                            v-model="parames.causeSubjectIds"
                            :options="subjectData">
                          </el-cascader>
                        </el-form-item>
                      </el-col>
                      <!-- <el-col :span="12" style="margin-top:15px">
                        <el-form-item label="支出事由:">
                          <el-input size="small" v-model="parames.expenditureCause" placeholder="请输入"></el-input>
                        </el-form-item>
                      </el-col> -->
                      <el-col :span="12" style="margin-top:15px">
                        <el-form-item label="收款人姓名:">
                          <el-input size="small" v-model="parames.payeeName" placeholder="请输入"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="收款人账号:">
                          <el-row>
                            <el-col :span="10">
                              <el-select style="width:100%" v-model="parames.receiptAccountType" placeholder="请选择">
                                <el-option v-for="(item,index) in accountTypeList" :key="index" :label="item.desc" :value="item.name"></el-option>
                              </el-select>
                            </el-col>
                            <el-col :span="14">
                              <el-input size="small" v-model="parames.receiptAccount" placeholder="请输入"></el-input>
                            </el-col>
                          </el-row>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="开户银行:">
                          <el-input size="small" v-model="parames.depositBank" placeholder="请输入"></el-input>
                        </el-form-item>
                      </el-col>
                      <!-- <el-col :span="12">
                        <el-form-item label="审核人:">
                          <userTree v-model="parames.reviewerId" :currentValue="parames.reviewerId"></userTree>
                        </el-form-item>
                      </el-col> -->
                      <el-col :span="16">
                        <el-form-item label="备注信息:">
                          <el-input size="small" type="textarea" v-model="parames.remark" placeholder="请输入"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="支出附件:">
                          <el-upload
                            class="upload-demo"
                            multiple
                            :headers="myHeaders"
                            :action="fileAction"
                            :on-success="handleSucess"
                            :on-remove="handleRemove"
                            :file-list="file">
                            <el-button icon="el-icon-upload2" type="primary" plain style="width: 400px">点击上传</el-button>
                          </el-upload>
                        </el-form-item>
                      </el-col>
                    </a-collapse-panel>
                    <a-collapse-panel class="marginB10" header="支出明细" key="2">
                      <el-col :span="24" style="margin-top:15px">
                        <el-row id="addHet">
                          <el-col :span="6">产品名称</el-col>
                          <el-col :span="6">实收金额</el-col>
                          <el-col :span="6">可支出金额</el-col>
                          <el-col :span="6">本次支出</el-col>

                          <el-col :span="24" style="margin-top:15px">
                            <a-collapse :defaultActiveKey="tableKeys" :bordered="false">
                              <a-collapse-panel :key="index" :style="customStyle" v-for="(item,index) in parames.expenditureDetailList">
                                <div style="background:#fafafa;margin-left:14px" slot="header">
                                  <el-row>
                                    <el-col :span="12">
                                      <span>合同流水号:</span>
                                      <span>{{item.id}}</span>
                                    </el-col>
                                    <el-col :span="12" style="text-align:right">
                                      <span class="el-dropdown-link">
                                        <a-icon style="margin: 0 15px;" type="delete" @click="handleDelproduct(index,item)"/>
                                      </span>
                                    </el-col>
                                  </el-row>
                                </div>
                                <el-row style="padding: 15px" v-for="(itemp,indexp) in item.contractProductVOList" :key="indexp">
                                  <el-col :span="6">
                                    <span style="margin-left:15px">{{itemp.productName}}</span>
                                  </el-col>
                                  <el-col :span="6">
                                    <span style="margin-left:15px">{{itemp.receiptedAmount}}</span>
                                  </el-col>
                                  <el-col :span="6">
                                    {{itemp.expendableAmount}}
                                  </el-col>
                                  <el-col :span="6">
                                      <el-input v-model.number="itemp.applicationAmount" @blur="handleBlur(itemp)" size="small"></el-input>
                                      <p style="color:#f00" v-if="itemp.applicationAmount>itemp.expendableAmount">输入金额超过最大值</p>
                                  </el-col>
                                </el-row>
                              </a-collapse-panel>
                            </a-collapse>
                          </el-col>
                        </el-row>
                        <el-button icon="el-icon-plus" size="small" @click="handelAddProduct" style="width:100%;margin-top:20px">添加合同</el-button>
                      </el-col>
                    </a-collapse-panel>
                  </a-collapse>
                </el-row>
              </el-form>
            </el-col>
            <el-col :span="5" style="position: fixed;top:80px;right:-10px;width:240px">
              <div v-if="dialogData.type == 'edit'">
                <el-button
                  @click="handleCancle"
                  size="small"
                  icon="el-icon-close"
                  style="width:200px;text-align: left;margin-bottom:10px"
                >取消编辑</el-button>
              </div>
            </el-col>
        </el-row>
        
        <div class="from-bottom-box">
          <el-button size="small" type="primary" @click="handleSave">保存</el-button>
          <el-button size="small" @click="handleClose">取消</el-button>
        </div>
      </a-drawer>
      <hetongDialog :hetongData="hetongData" @watchSlect="watchSlect"></hetongDialog>
    </div>
</template>

<script>
import hetongDialog from './addZhichuHetong.vue'
export default {
    props: ['dialogData'],
    data() {
        return {
          customStyle: 'border-radius: 4px;margin-bottom: 8px;border: #f7f7f7 solid 1px;overflow: hidden',
          activeNames: ['1','2'],
          parames: {
            id: '',
            causeSubjectIds: [], //支出科目
            expenditureCause: '', //支出事由,
            causeSubjectId: '', // 支出科目,
            payeeName: '', //收款人姓名,
            receiptAccountType: '', //收款账号类型(枚举）,
            receiptAccount: '', //收款账号,
            depositBank: '', //开户银行,
            remark: '', //备注信息,
            // reviewerId: '', //审核人,
            attachmentSet:[],
            expenditureDetailList:[]
          },
          tableKeys: [0,1,2,3],
          fileList: [],
          file: [],
          myHeaders: {authorization: ''},
          fileAction: this.$api.postFinanceExpenditureAttachmentUpload, //附件上传地址
          hetongData: {
            title: '',
            slectData: [],
            show: false
          },
          rules: {
            causeSubjectIds: [{ required: true, message: '必填', trigger: ['change','blur' ]}],
            receiptDate: [{ required: true, message: '必填', trigger: ['blur' ]}],
          },
          accountTypeList: [], //帐户类型
          subjectData: [] //科目
        };
    },
    created() {

    },
    mounted() {

    },
    methods: {
      handleClose () { //关闭弹窗
        this.dialogData.show = false
      },
      handleCancle () { //取消重新编辑
        this.dialogData.show = false
        this.$emit('checkOpen')
      },
      handleBlur (item) { //输入价格失去焦点
       var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 //判断正整数 /^[1-9]+[0-9]*]*$/
    　　if (!re.test(item.handleBlur)) {
    　　　　item.handleBlur = ''
    　　　　return false;
    　　}
      },
      handleSucess (response,fileList) { //上传附件成功返回url
        this.fileList.push({
            name: response.data.name,
            url: response.data.url
        })
      },
      handleRemove (file) { //删除附件更新
          this.fileList.forEach((el,index)=>{
              if (file.response) {
                  if (el.url == file.response.data.url) {
                      this.fileList.splice(index, 1)
                  }
              } else {
                  if (el == file.url) {
                      this.fileList.splice(index, 1)
                  }
              }
          })
      },
      watchSlect (data) { //监听返回的选中的数组
        if (data.length > 0) {
          this.parames.expenditureDetailList = data
        }
      },
      handleDelproduct (index,row) { //删除当前行产品
        this.parames.expenditureDetailList.splice(index,1)
      },
      handelAddProduct () { //添加合同
        this.hetongData.title = '选择合同'
        this.hetongData.slectData = this.parames.expenditureDetailList
        this.hetongData.show = true
      },
      setData () {
        this.parames.expenditureCause = this.parames.causeSubjectIds[0]
        this.parames.causeSubjectId = this.parames.causeSubjectIds[1]
        let expenditureDetailList = []
        this.parames.expenditureDetailList.forEach(el=>{
          el.contractProductVOList.forEach(bl=>{
            if (bl.contractProductId) {
              expenditureDetailList.push({
                contractProductId: bl.contractProductId,
                applicationAmount: bl.applicationAmount?bl.applicationAmount:0
              })
            } else {
              expenditureDetailList.push({
                contractProductId: bl.id,
                applicationAmount: bl.applicationAmount?bl.applicationAmount:0
              })
            }
          })
        })
        this.parames.expenditureDetailList = expenditureDetailList
        this.parames.attachmentSet = this.fileList
      },
      handleSave () { //保存
        this.$refs['parames'].validate((valid) => {
          if (valid) {
            this.setData()
            if (this.dialogData.type == 'edit') { //修改保存成功
              this.$post(this.$api.postFinanceExpenditureEdit,this.parames).then(response => {
                if (response.data.succeed) {
                  this.$message({ type:'success',message: '修改成功'})
                  this.handleClose()
                  this.$emit('checkOpen','1') //重新打开父级弹窗
                }
              })
            } else { //新增
              this.$post(this.$api.postFinanceExpenditureAdd,this.parames).then(response => {
                if (response.data.succeed) {
                  this.$message({ type:'success',message: '保存成功'})
                  this.$emit('checkRender')
                  this.handleClose()
                }
              })
            }
            
          }
        })
      },
      render () { //获取详情信息
        this.loading = true
        this.$post(this.$api.postFinanceExpenditureFind,{
          expenditureRecordId: this.dialogData.id
        }).then(response => {
          if (response.data.succeed) {
            let data = response.data.data
            this.parames.id = data.id
            this.parames.expenditureCause = data.expenditureCause
            this.parames.causeSubjectId = data.causeSubjectId
            this.parames.payeeName = data.payeeName
            if (data.receiptAccountType) {
              this.parames.receiptAccountType = data.receiptAccountType.name
            }
            this.parames.receiptAccount = data.receiptAccount
            this.parames.depositBank = data.depositBank
            this.parames.remark = data.remark
            this.parames.causeSubjectIds = [data.expenditureCause, data.causeSubjectId]
            let origan = data.expenditureDetailList
            this.parames.expenditureDetailList = this.$utils.unique(origan)
            this.fileList = data.attachmentSet
            data.attachmentSet.forEach(el=>{
                this.file.push({
                    name: el.name,
                    url: el.url
                })
            })
            for (var i = 0; i < origan.length; i++) {
              for (var j = 0; j < this.parames.expenditureDetailList.length; j++) {
                if (origan[i].contractId == this.parames.expenditureDetailList[j].id) {
                  this.parames.expenditureDetailList[j].contractProductVOList.push(origan[i])
                }
              }
            }
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      getTree () { //获取科目数据
        this.$post(this.$api.postExpenditureCauseTree).then(response => {
          if (response.data.succeed) {
            this.subjectData = []
            if (response.data.data.length > 0) {
              response.data.data.forEach(el=>{
                this.getData(el)
                if (el.label) {
                  this.subjectData.push(el)
                }
              })
            }
          }
        })
      },
      getData(data) { //处理树数据
        if (data.causeTypeName) {
          data.label = data.causeTypeName
        }
        if (data.causeSubjectName) {
          data.label = data.causeSubjectName
        }
        data.value = data.id
        data.children = data.causeSubjectList
        if (data.children && data.children.length > 0) {
          for(var i = 0; i < data.children.length; i++) {
            this.getData(data.children[i])
          }
        }
      },
      resetData () { //重置数据
        this.parames.id = ''
        this.parames.expenditureCause = '' //支出事由,
        this.parames.causeSubjectId = '' // 支出科目,
        this.parames.payeeName = '' //收款人姓名,
        this.parames.receiptAccountType = '' //收款账号类型(枚举）,
        this.parames.receiptAccount = '' //收款账号,
        this.parames.depositBank = '' //开户银行,
        this.parames.remark = '' //备注信息,
        this.parames.applicationDate = '' //申请时间,
        this.parames.applicationPerson = '' //申请人,
        this.parames.cashierReviewer = '' //出纳审核人,
        this.parames.cashierReviewDate = '' //出纳审核时间,
        this.parames.businessReviewer = '' //业务审核人,
        this.parames.businessReviewDate = '' //业务审核时间,
        this.parames.financeReviewer = '' //财务审核人,
        this.parames.financeReviewDate = '' //财务审核时间,
        this.parames.attachmentSet = []
        this.file = []
        this.fileList = []
        this.parames.expenditureDetailList =[]
       this.$refs.parames.resetFields()
      }
    },
    components: {
      hetongDialog
    },
    computed: {
      changeDialog () {
        return this.dialogData.show
      }
    }, 
    watch: {
      changeDialog: {
        handler (curVal, oldVal) {
          if (curVal) {
            this.getTree()
            this.myHeaders.authorization = this.$utils.getLocalStorage('usertoken')
            this.$utils.getEnumberation('postProviderAccountType','accountTypeList',this) //账户类型
            if (this.dialogData.type == 'edit') {
              this.render()
            }
          } else {
            this.resetData()
          }
        }
      }
    },
};
</script>

<style>
#addHet .ant-collapse > .ant-collapse-item > .ant-collapse-header .ant-collapse-arrow{
  left: 15px;
}
#addHet .ant-collapse > .ant-collapse-item > .ant-collapse-header{
  background: #fafafa;
}
#addHet .ant-collapse > .ant-collapse-item{
  border-bottom: #f7f7f7 solid 1px!important;
}
</style>
